//
//  EmoticonViewController.swift
//  表情键盘
//
//  Created by LiHong on 15/11/6.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit

class EmoticonViewController: UIViewController {

    //MARK: - 属性
    let collectionViewCellIdentifier = "collectionViewCellIdentifier"
    
    weak var textView: UITextView?
    private let baseTag = 1000
    override func viewDidLoad() {
        super.viewDidLoad()

        
        prepareUI()
    }
    
    // 准备UI
    private func prepareUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        //VFL
        let views = ["cv" : collectionView , "tb" : toolBar]
        //collectionView水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        //toolBar水平方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        setupCollectionView()
        setupToolBar()
        
        
    }
    // 设置工具栏
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        
        var index = 0
        for package in packages {
            let name = package.group_name_cn
            
            let button = UIButton()
            //设置标题
            button.setTitle(name, forState: UIControlState.Normal)
            //设置背景
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            // 添加点击事件
            button.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.sizeToFit()
            
            
            button.tag = index + baseTag
            // 登录马上点亮第一个
            if index == 0 {
                switchSelectedButton(button)
            }
            
            let item = UIBarButtonItem(customView: button)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
          
            
            index++
        }
        items.removeLast()
        
        toolBar.items = items
    }
    /// 设置collectionView
    private func setupCollectionView() {
        collectionView.backgroundColor = UIColor(white: 0.85, alpha: 1)
        
        collectionView.dataSource = self
        
        collectionView.delegate = self
        
        collectionView.registerClass(emoticonCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
    }
    
//    //MARK: - 把表情插入到textView中
//    private func insertEmoticon(emoticon: Emoticon) {
//        guard let textView = self.textView else {
//            print("textView为空")
//            return
//        }
//        // 插入emoji表情
//        if let emoji = emoticon.emoji {
//            textView.insertText(emoji)
//        }
//        
//        if let pngPath = emoticon.pngPath {
//            // 附件,图片可以作为附件,附件可以添加到属性文本
//            let attachment = LHTextAttachment()
//            attachment.image = UIImage(contentsOfFile: pngPath)
//            // 将表情图片的名称赋值
//            attachment.name = emoticon.chs
//            
//            let height = textView.font?.lineHeight ?? 10
//            //设置附件的大小
//            attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
//            
//         //   let attrString = NSAttributedString(attachment: attachment)
//            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            attrString.addAttribute(NSFontAttributeName, value: textView.font!, range: NSRange(location: 0, length: 1))
//            
//            let attrStringM = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            let selectedRange = textView.selectedRange
//            
//            attrStringM.replaceCharactersInRange(selectedRange, withAttributedString: attrString)
//            
//            textView.attributedText = attrStringM
//            
//            textView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
//        }
//        
//        
//    }
    
    
    //MARK: - Item点击事件
    func itemClick(button: UIButton) {
  //      print(button.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: button.tag - baseTag)
        
        collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.Left)
        switchSelectedButton(button)
    }
    // 点击后常亮
    private var selectedButton: UIButton?
    
    private func switchSelectedButton(button: UIButton) {
        selectedButton?.selected = false

        button.selected = true
        
        selectedButton = button
    }
    
    //MARK: - 懒加载
    ///collectionView
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: emoticonLayout())
    
    ///toolBar
    private lazy var toolBar = UIToolbar()
    
    ///表情包模型
    private lazy var packages = EmoticonPakage.packages

}
//MARK: - 扩展实现协议
extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
      //  print(packages.count)
        return packages.count
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons?.count  ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! emoticonCell
        
        let emoticon = packages[indexPath.section].emoticons?[indexPath.item]
     //   cell.backgroundColor = UIColor.randomColor()
        cell.emoticon = emoticon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons?[indexPath.item]
      //  print("点击了emoticon = \(emoticon)")
    //    insertEmoticon(emoticon!)
        textView?.insertEmoticon(emoticon!)
        
        if indexPath.section != 0{
            
            EmoticonPakage.addFavorate(emoticon!)
        }
        
        collectionView.reloadSections(NSIndexSet(index: 0))
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let indexPath = collectionView.indexPathsForVisibleItems().first
        let section = indexPath!.section
        
        let button = toolBar.viewWithTag(section + baseTag) as! UIButton
        
        switchSelectedButton(button)
    }
}

///MARK: - 自定义cell
class emoticonCell: UICollectionViewCell {
    
    //MARK: - 属性
    var emoticon: Emoticon? {
        didSet {
            if let pngPath = emoticon?.pngPath {
                emoticonButton.setImage(UIImage(contentsOfFile: pngPath), forState: UIControlState.Normal)
            }else {
                emoticonButton.setImage(nil, forState: UIControlState.Normal)
            }
            
            //显示emoji表情
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            emoticonButton.userInteractionEnabled = false
            
            if emoticon!.removeEmoticon {
                //是删除按钮
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
            
        }
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 准备UI
    private func prepareUI() {
        contentView.addSubview(emoticonButton)
        
        //向内偏移
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
      //  emoticonButton.backgroundColor = UIColor.randomColor()
    }
    //MARK: - 懒加载
    private lazy var emoticonButton: UIButton = UIButton()
}

///MARK: - 自定义layout
class emoticonLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        //宽度
        let width = collectionView!.frame.width / 7.0
        //高度
        let height = collectionView!.frame.height / 3.0
        //item尺寸
        itemSize = CGSize(width: width, height: height)
        //滚动方向水平
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0

        collectionView?.bounces = false

        collectionView?.alwaysBounceHorizontal = false
        
        collectionView?.showsHorizontalScrollIndicator = false

        collectionView?.pagingEnabled = true
    }
}